package cn.thoughtworks.school.usercenter.controllers;

import cn.thoughtworks.school.usercenter.entities.PasswordReset;
import cn.thoughtworks.school.usercenter.entities.User;
import cn.thoughtworks.school.usercenter.exceptions.BusinessException;
import cn.thoughtworks.school.usercenter.repositories.PasswordResetRepository;
import cn.thoughtworks.school.usercenter.repositories.UserRepository;
import cn.thoughtworks.school.usercenter.services.SendEmailService;
import cn.thoughtworks.school.usercenter.utils.Md5Util;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/api/password-reset")
public class PasswordResetController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordResetRepository passwordResetRepository;

    @Autowired
    private Md5Util md5Util;

    @Autowired
    private SendEmailService sendEmailService;

    private final int TIME_LIMIT = 1800;
    private final int MILLIS_TIME = 1000;

    @Value("${emailDomain.url}")
    private String emailDomain;

    @RequestMapping(method = RequestMethod.POST)
    ResponseEntity createPasswordReset(@RequestBody Map<String, String> emailInfo) throws Exception {
        String email = emailInfo.get("email");
        User user = userRepository.findByEmail(email);
        if (user == null) {
            throw new BusinessException("找不到该邮箱的账户");
        }
        List<PasswordReset> passwordResets = passwordResetRepository.getPasswordResetByUserIdOrderByCreateTimeDesc(user.getId());
        if (passwordResets.size() != 0) {
            PasswordReset passwordReset = passwordResets.get(0);//找距离当前时间最近的一条
            long timeInterval = (Calendar.getInstance().getTimeInMillis() / MILLIS_TIME)
                    - passwordReset.getCreateTime().getTime() / MILLIS_TIME;
            if (TIME_LIMIT > timeInterval) {
                throw new BusinessException("已经发送过邮件了");
            }
        }
        PasswordReset passwordReset = new PasswordReset();
        passwordReset.setUserId(user.getId());
        passwordReset.setVaild(true);
        passwordReset.setCreateTime(new Timestamp(new Date().getTime()));
        passwordReset = passwordResetRepository.save(passwordReset);
        String uuId=passwordReset.getUuId();
        HttpResponse response = sendPasswordResetEmail(email, uuId);
        if (response.getStatusLine().getStatusCode() == 200) {
            return new ResponseEntity(HttpStatus.CREATED);//发送邮件成功
        } else {
            throw new BusinessException("发送邮件失败");
        }
    }
    @RequestMapping(method = RequestMethod.PUT)
    ResponseEntity resetPassword(@RequestBody Map<String, String> passwordInfo) throws Exception {
        String newPassword = passwordInfo.get("newPassword");
        String confirmPassword = passwordInfo.get("confirmPassword");
        String uuId = passwordInfo.get("uuId");
        if (!newPassword.equals(confirmPassword)) {
            throw new BusinessException("两次输入的密码不等啦");
        }
        PasswordReset passwordReset = passwordResetRepository.findByUuId(uuId);
        if (passwordReset == null) {
            throw new BusinessException("uuId不对啦");
        }
        if (!passwordReset.getVaild()) {
            throw new BusinessException("已经修改过了");
        }
        long timeInterval = (Calendar.getInstance().getTimeInMillis() / MILLIS_TIME)
                - passwordReset.getCreateTime().getTime() / MILLIS_TIME;
        if (TIME_LIMIT <= timeInterval) {
            throw new BusinessException("链接过期啦");
        }
        User user = userRepository.findById(passwordReset.getUserId()).orElseThrow(() -> new BusinessException("当前用户不存在"));
        user.setPassword(md5Util.getMD5(md5Util.getMD5(newPassword)));
        userRepository.save(user);
        passwordReset.setVaild(false);
        passwordResetRepository.save(passwordReset);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    private HttpResponse sendPasswordResetEmail(String email, String uuId) throws IOException {

        String linkAddress = emailDomain + "?uuId=" + uuId;
        String subject = "重置密码";

        String emailContent = "您在访问我们网站时点击了忘记密码链接，这是一封密码重置确认邮件。\n 您可以通过点击以下链接重置帐户密码:\n" + linkAddress + "\n为保障您的帐号安全，请在30分钟内点击该链接，您也可以将链接复制到浏览器地址栏访问。\n 若如果您并未尝试修改密码，请忽略本邮件，由此给您带来的不便请谅解。本邮件由系统自动发出,请勿直接回复!";
        return sendEmailService.sendEmail(email, subject, emailContent);
    }
}
